package com.zhibang.controller;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhibang.dto.ShopDTO;
import com.zhibang.entity.Shop;
import com.zhibang.mapstruct.ShopMapstruct;
import com.zhibang.service.ShopService;
import com.zhibang.util.Result;
import com.zhibang.vo.ShopCasVo;
import lombok.Data;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @autor 流萤微微
 * @date 2025年03月08日 9:05
 */
@RestController
@RequestMapping("/shop")
public class ShopController {
    @Resource
    private ShopService shopService;

//    获取门店列表级联数据
    @RequestMapping("/cas")
    public Result cas(){
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("pcode",0);
        qw.select("id,name");
        List<Shop> list =shopService.list(qw);
        List<ShopCasVo> vos = ShopMapstruct.instance.toShopCasVoList(list);
//      然后查询到每个总店对应的子店
        vos.forEach(vo->{
            qw.clear();//清空条件
            qw.eq("pcode",vo.getValue());
            List<Shop> child = shopService.list(qw);
            List<ShopCasVo > childVos = ShopMapstruct.instance.toShopCasVoList(child);
            vo.setChildren(childVos);
        });
        return Result.data(vos);
    }

    // 查询所有商品+分页
    @RequestMapping("list/{page}/{rows}")
    public Result list(@RequestBody Shop shop,
                       @PathVariable Integer page,
                       @PathVariable Integer rows) {
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(shop.getName()), "name", shop.getName());
        qw.like(StringUtils.isNotBlank(shop.getCode()), "code", shop.getCode());
        IPage<Shop> iPage = new Page<>(page,rows);
        //判断pcode等于0
        qw.eq("pcode", 0);
        shopService.page(iPage,qw);
        return Result.data(iPage);
    }

    // 添加总店
    @RequestMapping("/addshop") // 明确指定为 POST 方法
    public Result add(@RequestBody Shop shop) {
        //随机生成一个100000-999999 之间的随机数
        shop.setCode(String.valueOf((int)((Math.random()*9+1)*100000)));
        // 设置 pcode 为 0（表示总店）
        shop.setPcode("0");
        // 设置其他默认值
        shop.setState(0);
//        createTime设为系统当前时间  String类型  格式：yyyy-MM-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        shop.setCreateTime(sdf.format(new Date()));
        // 保存到数据库
        boolean isSuccess = shopService.save(shop);
        return isSuccess ? Result.ok("添加成功") : Result.fail("添加失败");
    }

    @RequestMapping("/gjzdcxfd")
    //根据总店id查询 子店pcode
    public Result edit(@RequestBody Shop shop) {
        // 查询总店id
        Shop shop1 = shopService.getById(shop.getId());
        // 根据总店id查询子店
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("pcode", shop1.getId());

        // 返回子店信息
        List<Shop> list = shopService.list(qw);
        return Result.data(list);
    }


    @RequestMapping("/fendian/{page}/{rows}")
    public Result fendian(@RequestBody Shop shop,
                          @PathVariable Integer page,
                          @PathVariable Integer rows){
        //查询分店
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(shop.getName()),"name",shop.getName());
        qw.like(StringUtils.isNotBlank(shop.getProvince()),"province",shop.getProvince());
        qw.like(StringUtils.isNotBlank(shop.getCity()),"city",shop.getCity());
        qw.like(StringUtils.isNotBlank(shop.getCountry()),"country",shop.getCountry());
        IPage<Shop> ip =new Page<>(page,rows);
        //pcode不等于0
        qw.ne("pcode",0);
        shopService.page(ip,qw);
        return Result.data(ip);
    }

    @RequestMapping("/update")
    public Result update(@RequestBody Shop shop){
        return Result.data(shopService.updateById(shop));
    }

    // 根据分店ID查询总店信息
    @RequestMapping("/zondian1")
    public Result getParentStore(@RequestBody Shop shop) {
        Shop branch = shopService.getById(shop.getId());
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("id", branch.getPcode());
        List<Shop> parentStores = shopService.list(qw);
        return Result.data(parentStores);
    }

    // 添加分店
    @RequestMapping("/addBranch")
    public Result addBranch(@RequestBody Shop shop) {
        // 随机生成一个642-100000 之间的随机数
        shop.setCode(String.valueOf((int)((Math.random()*9+1)*100000)));
        shop.setState(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        shop.setCreateTime(sdf.format(new Date()));
        boolean isSuccess = shopService.save(shop);
        return isSuccess ? Result.ok("添加成功") : Result.fail("添加失败");
    }
    //查询全部总店
    @RequestMapping("/zondian")
    public Result zondian(){
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("pcode",0);
        List<Shop> list = shopService.list(qw);
        return Result.data(list);
    }

    @RequestMapping("/list2")
    @RequiresUser
    public Result list(){
        //先查询到所有的总店
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("pcode",0);
        qw.select("id,name");
        List<Shop> shops = shopService.list(qw);
        List<ShopCasVo> vos = ShopMapstruct.instance.toShopCasVoList(shops);
        //然后查询到每个总店对应的子店
        vos.forEach(vo -> {
            qw.clear(); //清空条件
            qw.eq("pcode",vo.getValue());
            List<Shop> list = shopService.list(qw);
            List<ShopCasVo> child = ShopMapstruct.instance.toShopCasVoList(list);
            vo.setChildren(child);
        });
        return Result.data(vos);
    }
}


